using System.Reflection;
using NLog.Web;
using SqlSugar;

using Infrastructure.Data;
using MySql.Data.MySqlClient;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

// 配置Dapper
var mysqlConnectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddScoped<DapperInitializer>(sp => 
    new DapperInitializer(mysqlConnectionString));
builder.Services.AddTransient<MySqlConnection>(sp => 
    new MySqlConnection(mysqlConnectionString));

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();


//中介者
builder.Services.AddMediatR(cfg => {
    cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly());
});
//映射
builder.Services.AddAutoMapper(typeof(MappingProfile));
//日志
builder.Host.UseNLog();

var app = builder.Build();
//跨域
app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());



// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

// 应用启动时执行Dapper初始化
using (var scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;
    try
    {
        var dapperInitializer = services.GetRequiredService<DapperInitializer>();
        dapperInitializer.Initialize();
        Console.WriteLine("Dapper database initialization completed.");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Dapper initialization failed: {ex.Message}");
        throw;
    }
}

app.Run();